import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import detector from 'i18next-browser-languagedetector';
import resourcesToBackend from 'i18next-resources-to-backend';
const i18n = i18next.createInstance();
const moduleNames = [
  { key: 'common', name: 'common' },
  { key: 'layout', name: 'layout' },
  { key: 'login', name: 'login' },
  { key: 'register', name: 'register' },
  { key: 'app', name: 'app' },
  { key: 'appOverview', name: 'app-overview' },
  { key: 'appDebug', name: 'app-debug' },
  { key: 'appApi', name: 'app-api' },
  { key: 'appAnnotation', name: 'app-annotation' },
  { key: 'share', name: 'share-app' },
  { key: 'dataset', name: 'dataset' },
  { key: 'datasetDocuments', name: 'dataset-documents' },
  { key: 'datasetHitTesting', name: 'dataset-hit-testing' },
  { key: 'datasetSettings', name: 'dataset-settings' },
  { key: 'datasetCreation', name: 'dataset-creation' },
  { key: 'explore', name: 'explore' },
  { key: 'billing', name: 'billing' },
  { key: 'custom', name: 'custom' },
  { key: 'tools', name: 'tools' },
  { key: 'workflow', name: 'workflow' },
  { key: 'runLog', name: 'run-log' },
];
const loadLangResources = async (lang: string) => {
  const allModule: Array<Promise<any>> = [];
  moduleNames.forEach((module) => {
    allModule.push(import(`./${lang}/${module.name}.ts`));
  });
  const moduleR = await Promise.all(allModule);
  const translation: Record<string, any> = {};
  moduleNames.forEach((m, i) => {
    translation[m.key] = moduleR[i].default;
  });
  return translation;
};

await i18n
  .use(detector)
  .use(initReactI18next) // passes i18n down to react-i18next
  .use(
    resourcesToBackend(async (language: string, namespace: string, callback) => {
      let lng = language;
      if (language === 'zh') lng = 'zh-Hans';

      console.log(language, namespace);

      const resources = await loadLangResources(lng);
      callback(null, resources);
    }),
  )
  .init({
    lng: 'zh-Hans',
    defaultNS: 'translation',
    fallbackLng: 'en-US',
  });

export default i18n;
